<?php


class School_model extends MY_Model {
	
	
	/**
	 * Constructor
	 */
	function School_model() {
		parent::__construct();
	}


	
	/**
	 * retrieve information about one or all hotels associated to this school
	 * @param $hotelId choose a specific hotel
	 * @todo ... and if there is no hotel associated to this school
	 * @return array with hotels info or empty array if no hotel retrieved 
	 */
	public function getHotelsInfo($hotelId = null) {
		
		$user_id = $this->ion_auth->get_user()->id;
		
		if ($hotelId) {
			$this->db->select('*')->from('users')->where('users.id',$hotelId);
			$this->db->join('meta', 'meta.user_id = users.id');
			$this->db->join('sh', 'sh.hotel_id = users.id');
			$this->db->where('sh.school_id', $user_id);
			$hotelInfo = $this->db->get()->row();
			
			$this->db->flush_cache();

			$this->db->select('hotelPayment')->from('sh');
			$this->db->where('school_id', $user_id);
			$this->db->where('hotel_id', $hotelId);
			$hotelInfo->hotelPayment = $this->db->get()->row()->hotelPayment;
			
			return $hotelInfo;
		}
		
		$this->db->select('hotel_id')->from('sh')->where('school_id', $user_id);
		
		$result = $this->db->get()->result();
		
		$hotelIDs = array();
		
		foreach ($result as $item) {
			array_push($hotelIDs, $item->hotel_id);
		}
		
		$this->db->flush_cache();
		
		$result = array();
		
		if (!empty($hotelIDs)) {
			$this->db->select('*')->from('users')->where_in('users.id',$hotelIDs);
			$this->db->join('meta', 'meta.user_id = users.id');
			$result = $this->db->get()->result();
		}
		
		return $result;
	}
	
	/**
	 * Get an array with IDs of all available offers from the current login user
	 */
	public function getOfferIds() {
		$user_id = $this->ion_auth->get_user()->id;
		$offer_ids = array();
		$Q = $this->db->select('id')->from('offer')->where('users_id',$user_id)->get();
		$data = $Q->result();
		$Q->free_result();
		foreach ($data as $item) { array_push($offer_ids, $item->id); }
		return $offer_ids;
	}	

	public function getLastClassScheduled($offerId = null) {

		if ( $offerId == null) return null;

		$Q = $this->db->select_max('class_id')->from('schedule')->where('offer_id',$offerId)->group_by('offer_id')->get();
		$data = $Q->result();
		$Q->free_result();

		if ($data == null) return null;
		else return $data[0]->class_id;
	}

	/**
	 * Number of schedules from the given class
	 * @param int $classId
	 * @return int quantity with the number of schedules from the given class or null if there is no records
	 */
	public function getLastScheduleQuantity($classId = null) {

		if ( $classId == null ) return null;

		$Q = $this->db->select('count(class_id) as quantity')->from('schedule')->where('class_id',$classId)->get();
		$data = $Q->result();
		$Q->free_result();

		if ( $data == null) return null;
		else return $data[0]->quantity;
	}

	public function addSchedule($schOptions, $fullCallOptions) {

		// required fields
		if (!$this->_required(array('class_id','offer_id','start','end'), $schOptions))
			return false;

		// default values
		$fullCallOptions = $this->_default(
			array(
				'editable'	=>1,
				'allDay'	=>0,
				'color'=> 	'blue',
			), 
			$fullCallOptions
		);

		$result = $this->db->insert('schedule', $schOptions);

		if ( $result ) {

			$fullCallOptions['schedule_id'] = $this->db->insert_id(); 

			$result = null;
			$result = $this->db->insert('fullcalevent', $fullCallOptions);

			if ( $result )
				return $fullCallOptions['schedule_id'];
			else
				return false;
		}
		else
			return false;
	}

	public function getOffers2Schedule() {

		$offer_ids = $this->getOfferIds();

		$this->db->select_max('class_id')->from('schedule');

		$this->db->where_in('offer_id',$offer_ids);

		$this->db->group_by('offer_id'); 

		$result = $this->db->get()->result();

		$class_ids = array();

		foreach ($result as $item) { array_push($class_ids, $item->class_id); }

		$result = array();
		$this->db->flush_cache();

		$this->db->select('schedule.offer_id');
		$this->db->select('schedule.class_id as last_class_id_scheduled');
		$this->db->select('count(class_id) as quantity');

		$this->db->from('schedule')->where_in('class_id',$class_ids);

		$this->db->group_by('offer_id'); 

		$result = $this->db->get()->result();

		$remainingClasses = array();

		foreach ($result as $item) { $remainingClasses[$item->offer_id] = $item->quantity; }

		$offers = $this->getOffer(array('active' => 'yes'));

		foreach ($offers as $offer) { 
			if (isset($remainingClasses[$offer->id])) 
				$offer->remainingClasses = $remainingClasses[$offer->id];
			else 
				$offer->remainingClasses = $offer->numberOfClasses;
		}

		//$this->firephp->log($offer_ids,'ids');
		return $offers;
	}
	
	/**
	 * Get offer's 
	 * Options: Optional Values
	 * ------------------------
	 * offerId			- id of the offer 			(int)
	 * active			- if it is active or not 	('yes'/'no')
	 * visible			- if it is visble or not 	('yes'/'no')
	 * name				- name of the offer			(varchar)
	 * available		- true/false (boolean) or 'both' if this option is omited 		
	 * @param array $options
	 * @return $data with available offers or false if no offers available
	 */
	public function getOffer($options = array()) {
		
		$dataTypeJSON 	= 'json';	// normal JSON format
		$dataTypeARRAY	= 'array';	// data is stored in an ARRAY
		$dataTypeJTABLE	= 'jtable';	// data formated for JTABLE 
		
		// who is asking for this?
		$user_id = $this->ion_auth->get_user()->id;
		
		// default fields
		$options = $this->_default(array('datatype' => 'array', ), $options);
		
		$this->db->select('*');
		
		$this->db->from('offer');
		
		// only show offers of the current logged in user
		$this->db->where('users_id',$user_id);
		
		// optional conditions
		if (isset($options['offerId']))
			$this->db->where('id',$options['offerId']);
		if (isset($options['active']))
			if ($options['active'] == 'yes')
				$this->db->where('active',1);
			else if ($options['active'] == 'no')
				$this->db->where('active',0);
		if (isset($options['visible']))
			if ($options['visible'] == 'yes')
				$this->db->where('visible',1);
			else if ($options['visible'] == 'no')
				$this->db->where('visible',0);
		if (isset($options['name']))
			$this->db->where('name',$options['name']);
		if (isset($options['available']))
			if ($options['available'] == true)
				$this->db->where('remainingClasses >',0);
			else if ($options['available'] == false)
				$this->db->where('remainingClasses',0);
		
		// get the data if exists
		$query = $this->db->get();
		
		// no data? return an empty json object
		if ($query->num_rows() == 0) {
			return false;
			//return '{ "Result":"OK", "Records":[]}';
		}
		
		// return only one record if 'id' field is set
		if (isset($options['offerId'])) {
			return $query->row();
		}
		
		return $query->result();
	}
	
	/**
	 * Create Offer and return that offer in JSON format
	 */
	public function addOffer($data) {
		
		// all new offers are visible
		$data['visible'] = 1;
		
		// set the id of the corrente school user
		$this->db->set('users_id',$this->ion_auth->get_user()->id);
		
		// set all data fields passed in the POST
		$this->db->set($data);
		
		// insert data 
		$this->db->insert('offer');
		
		// select the last inserted record table offer 
		$query 		= $this->db->query("select * from offer where id=(select max(id) from offer);");
		
		// the result will be fetched into the first indice of this array (the previous select returns only one row)
		$data_array = $query->result();

		// format the array ... "Record" should only have one registry, in this case the first and only array index
		$final_arr 	= array("Result"=>"OK","Record"=>$data_array[0]);
		
		// translate to json format
		$json 		= json_encode($final_arr); 	
		
		// return the last offer inserted to DB in json format
		return $json;
	}
	
	/**
	 * Delete Offer
	 * @param Int $id of the offer to be deleted 
	 */
	public function deleteOffer($id) {
		$tmp_where  = $this->db->where('id',$id);
		$tmp_delete = $this->db->delete('offer');
	}
	
	/**
	 * Update Offer
	 * @param array $post array with all fields to be updated
	 */
	public function updateOffer($post) {
		$this->db->update('offer',$post,array('id'=>$post['id']));
	}	
	
	
	
	
	
	
	
	/**
	 * Create a new record in the db table 'extra'
	 * @param array $post array with all extra fields to be inserted 
	 * @return object return false if no data was inserted or the record inserted in jtable json format 
	 */
	public function createExtra($post) {
		
		$users_id = $this->ion_auth->get_user()->id;
		
		$this->db->set('users_id',$users_id);

		$succ = $this->db->insert('extra',$post);
		
		if ($succ) {
			$this->db->select_max('id');
			$query = $this->db->get('extra');
			$row = $query->row();
			$extraId = $row->id;
			return $this->readExtra($extraId);
		}
		else {
			return false;	
		}
	}
	
	
	
	/**
	 * Get extra items in jtable format 
	 * @param id $id - the extra identification if we only want one record ('null' for all extras)
	 * @param offerId $offerId - The offer identification if we only want extras associated to a specific offer
	 */
	public function readExtra($id = null,$offerId = null) {
		
		$users_id = $this->ion_auth->get_user()->id;
		
		$this->db->select('*');
		$this->db->from('extra');
		
		if ($id != null)
			$this->db->where('id',$id);
		
		$this->db->where('users_id', $users_id);
		
		if ($offerId != null) {
			$this->db->join('extra_offer','extra_offer.extra_id = extra.id');
			$this->db->where('offer_id', $offerId);
		}
		
		$query = $this->db->get();
			
		if ($query->num_rows() == 0)
			return false;
			
		$rows = $query->result(); 
		
		$jTableResult['Result'] = 'OK';
		
		// if 'id' is set ... we only want the first and only record
		if ($id)
			$jTableResult['Record'] 	= $rows['0'];
		else
			$jTableResult['Records'] 	= $rows;
		
		return json_encode($jTableResult);
	}
	
	
	
	public function updateExtra($post) {
		$res = $this->db->update('extra',$post,array('id'=>$post['id']));
		return $res;
	}
	
	public function deleteExtra($id) {
		$this->db->where('id',$id);
		$res = $this->db->delete('extra');
		return $res;
	}
	
		
		
	
	
	/**
	 * Function to retrieve extras from the db
	 * @param array with the following optional fields [users_id,active,included_in_offer,offer_id(dont show the extras already included in this offer)]
	 * @todo try to merge the 'extra' related functions later
	 * @return Array with extras or empty array
	 */
	public function getExtra($extrasIDs = null, $options = null) {
		
		// ... if we have the IDs
		if ($extrasIDs)
			return $this->db->select('*')->from('extra')->where_in('id',$extrasIDs)->get()->result();
		
		if (!$options)
			return array();
	
		// get all extras included in the given offer
		if (isset($options['offer_id'])) {
			$this->db->select('extra_id')->from('extra_offer');
			$result = $this->db->where('offer_id',$options['offer_id'])->get()->result();
			$extrasIncluded = array();
			foreach ($result as $item) {
				array_push($extrasIncluded, $item->extra_id);
			}
		}
		
		$this->db->select('*')->from('extra');
	
		// filter data if arg are passed
		if (isset($options['users_id']))
			$this->db->where('users_id',$options['users_id']);
		if (isset($options['active']))
			$this->db->where('active',$options['active']);
		if (isset($options['included_in_offer']))
			$this->db->where('included_in_offer',$options['included_in_offer']);
		
		// show the extras not included in the offer
		if (!empty($extrasIncluded))
			$this->db->where_not_in('id',$extrasIncluded);
	
		$result = $this->db->get()->result();
	
		if ($result)
			return $result;
		else
			return array();
	}
	
	
	
	
	
	

	/**
	 * Get an array with schedules
	 * -------------------------
	 * Options: Optional Values
	 * -------------------------
	 * id - only this schedule
	 * offer_id - schedule associated to this offer
	 * class_id - schedule associated to this class
	 * start - from this date ...
	 * end - to this date
	 * incompleteClasses - boolean to choose if schedules without class should be returned (true by default)
	 * @param array $options with conditional optional values
	 * @return array $result 
	 */
	public function getSchedule($options) {
		
		// who is asking for this?
		$user_id = $this->ion_auth->get_user()->id;
		
		// by default show incomplete classes
		if (!isset($options['incompleteClasses'])) {
			$options['incompleteClasses'] = true;
		}
		
		$mainSelect = '
			schedule.id 				as id, 
			offer.name 					as title, 
			schedule.start				as start, 
			schedule.end				as end,
			fullcalevent.editable		as editable,
			fullcalevent.allDay			as allDay,
		';
		
		$scheduleSettings = ' 
			fullcalevent.color			as color,
			fullcalevent.bgColor		as bgColor,
			fullcalevent.borderColor	as borderColor,
			fullcalevent.textColor		as textColor
		';
		
		$classSettings = ' 
			class.id					as classId,
			class.color					as classColor,
			class.bgColor				as classBgColor,
			class.borderColor			as classBorderColor,
			class.textColor				as classTextColor
		';
		
		$offerSettings = ' 
			offer.color					as color,
			offer.bgColor				as bgColor,
			offer.borderColor			as borderColor,
			offer.textColor				as textColor
		';
			
		$tmpSettings = '
			offer.users_id				as usersId
		';
		
		$this->db->select($mainSelect);
		//$this->db->select($scheduleSettings);
		$this->db->select($offerSettings);
		$this->db->select($classSettings);
		//$this->db->select($tmpSettings);
		
		$this->db->from('schedule');
		
		if (isset($options['class_id']))
			$this->db->where('class_id', 	$options['class_id']);
		
		// ... interval
		if (isset($options['start']))
			$this->db->where('start >',		$options['start']);
		if (isset($options['end']))
			$this->db->where('end <',		$options['end']);

		if (isset($options['id']))
			$this->db->where('id',			$options['id']);
		
		// dont show schedules with no classes
		if (!$options['incompleteClasses']) {
			$this->chromephp->log('dont show imcomplete classes');
			$this->db->where('schedule.class_id is not null');
		}
		
		$this->db->join('offer','offer.id = schedule.offer_id','inner');

		if (isset($options['offer_id']))
			$this->db->where('offer_id',	$options['offer_id']);
		
		// show only the events of the current logged in user 
		$this->db->where('offer.users_id',$user_id);
		
		$this->db->join('class','class.offer_id = offer.id','inner');
		
		$this->db->join('fullcalevent','fullcalevent.schedule_id = schedule.id','inner');
		
		$this->db->group_by('id');
		
		$result = $this->db->get()->result_array();
		
		return $result;
	}

	
	/**
	 * Retrieve all future schedules associated to the given class 
	 * @param int $classId
	 * @todo - the function with the same name in the hotel is almost the same as this one
	 * try to merge these two in to a single function
	 */
	public function getUpcommingSchedule($classId) {
		
		// get the id of the school associated to the hotel with the given userId
 		//$schoolId = $this->db->select('*')->from('sh')->where('hotel_id',$userId)->get()->row()->school_id;
		//$schoolId = $this->ion_auth->get_user()->id;
 		
 		$this->db->flush_cache();
		
		$now = date('Y-m-d H:i:s',time());
		
		$this->db->select('
			schedule.id			as scheduleId,
			schedule.start		as start,
			schedule.end		as end,
			class.offer_id		as offerId
		');
		
		$this->db->from('schedule');
		
		$this->db->join('class','class.id = schedule.class_id');
		
		$this->db->where('class.id',$classId);
		
		//$this->db->join('offer','offer.id = schedule.offer_id');
		//$this->db->join('users','users.id = offer.users_id');
		
		// return only the schedules from the school associated to the given hotel (userId)
		//$this->db->where('users.id',$schoolId);
		
		$query = $this->db->get();
		$result = $query->result();
		
		return $result;	
	}
	
	/**
	 * Retrieve information about all available classes from this school with all schedules after current time
	 * @return array with all classes or an empty array if no classes available
	 */
	public function getAvailableClasses() {
		
		$user_id = $this->ion_auth->get_user()->id;
		
		$now = date('Y-m-d H:i:s',time());
		
		// select all classes with schedules after 'now'
		$this->db->select('class_id, count(*) as qt');
		$this->db->from('schedule');
		$this->db->where('start >',$now);
		$this->db->join('offer','offer.id = schedule.offer_id');
		$this->db->join('users','users.id = offer.users_id');
		$this->db->where('users.id',$user_id);
		$this->db->group_by('class_id');
		
		$result = array();
		$result = $this->db->get()->result();
		
		// no classes? ... return empty array
		if ($result == null) return array();

		$classIDsAfterNow = array();
		
		foreach ( $result as $item ) { $classIDsAfterNow[$item->class_id] = $item->qt; }
		
		// all classes with id's from the previous select
		$this->db->select('class_id, count(*) as qt');
		$this->db->from('schedule');
		$this->db->where_in('class_id',array_keys($classIDsAfterNow));
		$this->db->group_by('class_id');
		
		$result = array();
		$result = $this->db->get()->result();

		// no classes? ... return empty array
		if ($result == null) return array();
		
		$classIDsAll = array();
		
		foreach ( $result as $item ) { $classIDsAll[$item->class_id] = $item->qt; }
		
		// the intersection gives us classes with only future schedules ...
		$intersect = array_intersect_assoc($classIDsAfterNow, $classIDsAll);

		// no classes to display because the intersection has no results
		if ($intersect == null) return array();
		
		$this->db->flush_cache();
		
		$select =
		'
			offer.users_id 					as schoolId,
		    meta.company					as schoolName,
		    offer.id						as offer_id,
		    class.id						as class_id,
			offer.name						as name,
			offer.price						as price,
			offer.level						as level,
			offer.maxPart					as maxPart,
			offer.numberOfClasses			as numberOfClasses,
		    (class.maxPart - class.part)	as spots
		';
		
		$this->db->select($select);
		
		$this->db->from('offer');
		
		$this->db->join('class','class.offer_id = offer.id');
		$this->db->join('users','users.id = offer.users_id');
		$this->db->join('meta','meta.user_id = users.id');
		
		$this->db->where('users.id',$user_id);
		$this->db->where_in('class.id',array_keys($intersect));
		
		$result = array();
		$result = $this->db->get()->result();
		
		return $result;
	}
	
	/**
	 * Get an array with all hotel IDs associated to the current school
	 * @return array with Hotel IDs 
	 */
	public function getHotels() {
		
		$school_id = $this->ion_auth->get_user()->id;
		
		// array to hold the IDs
		$hotelIDs = array();
		
		// select hotels associated to the given
		$this->db->select('hotel_id')->from('sh')->where('school_id',$school_id);	
		$result = $this->db->get()->result();
		
		// append IDs to array
		foreach ($result as $value) { array_push($hotelIDs,$value->hotel_id); }
		
		return $hotelIDs;
	}
	
	
	/**
	 * Function that retrieves all class IDs with schedules within the given date range
	 * @param date $start
	 * @param date $end
	 * @return array with class IDs or an empty array
	 */
	public function getClassesWithSchedulesInRange($start, $end) {
		
		$school_id = $this->ion_auth->get_user()->id;
		
		$classIDs = array();
		
		$this->db->select('class_id')->from('schedule');
		$this->db->join('offer','offer.id = schedule.offer_id','inner');
		$this->db->join('users','users.id = offer.users_id','inner');
		
		$this->db->where('start >', $start);
		$this->db->where('end <', $end);
		$this->db->where('users.id', $school_id);
		
		$this->db->group_by('class_id');
		
		$result = $this->db->get()->result();
		
		foreach ($result as $value) {
			array_push($classIDs, $value->class_id);
		}
		
		$this->db->flush_cache();
		
		return $classIDs;
	}
	
	
	/**
	 *  Client and reservation information of all clients with reserves in the given class
	 * @param $classID
	 */
	public function getClientsInClass($classID) {
		
		$selection = '
			reserve.date 			as reservationDate,
			reserve.total 			as total, 
			reserve.hotelPayment 	as hotelPayment, 
			client.id 						as clientId, 
			client.name 					as clientName, 
			client.address 					as clientAddress, 
			client.email 					as clientEmail, 
			client.phone 					as clientPhone, 
			client.birthday 				as clientBirthday,
			client.nationality 				as clientNationality,
			client.sex 						as clientSex,
			client.height 					as clientHeight,
			client.weight 					as clientWeight,
			client.info 					as clientInfo,
			meta.company 					as entityName,
			meta.phone 						as entityPhone,
			users.email 					as entityEmail,
		';
		
		$this->db->select($selection)->from('reserve');
		
		$this->db->where('class_id', $classID);
		
		$this->db->join('client', 'client.id = reserve.client_id', 'inner');
		$this->db->join('users', 'users.id = client.users_id', 'inner');
		$this->db->join('meta', 'meta.user_id = users.id', 'inner');
		
		$clients = $this->db->get()->result();
		
		return $clients;
	}
	
	
	
	
	/**
	 * @param  $offer - object with the offer 
	 * @return classId -
	 */
	public function addClass($offer) {
		
		$this->db->set('offer_id', $offer->id);
		$this->db->set('maxPart', $offer->maxPart);
		$this->db->set('minPart', $offer->minPart);
		$this->db->set('part', 0);
		$this->db->set('allDay', 0);
		$this->db->insert('class');
		$classId = $this->db->insert_id();
		return $classId;
	}
	
	
	/**
	 * Create an Event record in 'schedule' and 'fullcalevent' table
	 * ----------------------------------------------
	 * Options: Required Values
	 * ---------------
	 * offer_id		- id of the offer		(int)					
	 * eventStart	- when the event starts (datetime)	
	 * eventEnd		- when the event ends	(datetime)	
	 * 
	 * Options: Optional Values
	 * ---------------
	 * editable (tinyint), allDay(tinyint), color(varchar), bgColor(varchar), 
	 * borderColor(varchar), textColor(varchar)
	 *  
	 * @param array $options
	 * @return $id of the event if it was created, or 'false' if it was not created
	 */
	public function oldCreateSchedule($options) {
		
		// required fields
		if (!$this->_required(array('offer_id','eventStart','eventEnd'), $options))
			return false;
		
		// default values
		$options = $this->_default(
			array(
				'allDay'	=>0,
				'editable'	=>1,
				'color'=>'blue',
			), 
		$options);
			
		// get the fields to check if this is the last offer schedule
		$offer = $this->db->select('numberOfClasses, remainingClasses, minPart, maxPart')->from('offer')->where('id',$options['offer_id'])->get()->row();
		
		$this->db->flush_cache();
		
		// ... its the last schedule of this offer ?
		if (($offer->remainingClasses - 1 ) == 0){ 
			$classId = $this->_createClass($options['offer_id'],$offer);
			$this->db->set('class_id',$classId); 
		}
		else { // it isnt the last  ... 
			//$this->chromephp->log('its not the first and it is not the last either ...');
			$this->db->set('class_id',null); // ... this schedule isnt associated to any class
		}
		
		$this->db->flush_cache();
		
		// set data to be inserted 
		$this->db->set('offer_id',	$options['offer_id']);
		$this->db->set('start',		$options['eventStart']);
		$this->db->set('end',		$options['eventEnd']);
		
		$this->db->insert('schedule');

		// get the 'id' of the added event
		$id = $this->db->insert_id();
		
		// if the event was created 
		if ($id) {
			
			$this->db->flush_cache();
			
			// decrement one value to the number of available classes 
			$row = $this->db->select('remainingClasses')->from('offer')->where('id',$options['offer_id'])->get()->result();
			$remainingClasses = $row['0']->remainingClasses;
			$remainingClasses--;
			$this->db->flush_cache();
			$this->db->where('id',$options['offer_id']);
			$this->db->update('offer',array('remainingClasses'=>$remainingClasses));
			$this->db->flush_cache();
			
			// add data to fullcalevent
			$this->db->set('schedule_id',$id);
			if (isset($options['editable'])) 	$this->db->set('editable',		$options['editable']);
			if (isset($options['allDay']))		$this->db->set('allDay',		$options['allDay']);
			if (isset($options['color']))		$this->db->set('color',			$options['color']);
			if (isset($options['bgColor'])) 	$this->db->set('bgColor',		$options['bgColor']); 
			if (isset($options['borderColor'])) $this->db->set('borderColor',	$options['borderColor']); 
			if (isset($options['textColor'])) 	$this->db->set('textColor',		$options['textColor']); 
			$this->db->insert('fullcalevent');
		}
		
		// return the last record id added or false if no event was added 
		return $id; 
	}

	
	/**
	 * Delete Event
	 */
	public function deleteEvent() {
		
	}

	
	/**
	*
	* @param array $options
	* @return boolean $succ return TRUE if  updated, FALSE otherwise
	*/
	public function updateEvent($options) {
	
			
	}
	
	
	/**
	 * check if an event exists 
	 */
	public function isEvent($id) {
		
	}
	
	
	/**
	 * Add extras to the given reserve
	 * @param $clientReservesId
	 * @param $extrasIDs
	 */
	public function addExtras($clientReservesId, $extrasIDs=array()) {
	
		if (!$extrasIDs)
			return false;
	
		if (!$clientReservesId)
			return false;
	
		$inserted = false;
	
		foreach ($extrasIDs as $value) {
			$data = array(
					'extra_id'				=> $value,
					'client_reserves_id'	=> $clientReservesId
			);
			$inserted = $this->db->insert('extra_reserve',$data);
			if($inserted==false) break;
		}
	
		return $inserted;
	}
	
	
	/**
	 * create a new reservation with the associated extras 
	 * @param int $clientId
	 * @param int $classId
	 * @param array $extraIDs - array with extrasIDs
	 * @param string $transport - 'no' or 'yes'
	 * @return true - reservation created  
	 * @return false - reservation not created
	 */
	public function createReservation($clientId,$classId,$extrasIDs) {
		
		$now 		= date('Y-m-d H:i:s',time());
		
		$class = $this->db->select('offer_id, maxPart, part')->from('class')->where('id',$classId)->get()->row();
		
		$offer = $this->getOffer(array('offerId'=>$class->offer_id));
		
		$price = $offer[0]->price;
		
		$total = $price;
		
		if ($extrasIDs)
			$extras = $this->School_model->getExtra($extrasIDs, null);
		
		foreach ($extras as $extra) {
			$total += $extra->price;
		}
		
		$clientResData = array(
			'reserves_id' 		=> null,
			'hotelPayment' 		=> null,
			'total'				=> $total,
			'client_id' 		=> $clientId,
			'date' 				=> $now,
			'class_id'			=> $classId,
		);
				
		$succ = $this->db->insert('reserve',$clientResData);
		
		if ($succ) {
			
			$this->addExtras($this->db->insert_id(),$extrasIDs);
			
			$part = $class->part;
			
			// last reservation?
			if ($class->maxPart == ($class->part + 1)) {
				
				// enable offer
				$offer = $this->db->select('numberOfClasses')->from('offer')->where('id', $class->offer_id)->get()->row();
				$this->db->update('offer', array('remainingClasses'=>$offer->numberOfClasses,'part'=>0), array('id'=>$class->offer_id));
			}
			
			// increment the participant number
			$part++;
			$this->db->update('class',array('part'=>$part),array('id'=>$classId));
		
			return true;
		}
		else {
			return false;
		}
	}
	
	
	
	public function readReservation($options) {
		
		// who is asking for this?
		$user_id = $this->ion_auth->get_user()->id;
		
		//$this->db->select('offer.name as offerName, client.name as clientName, email, phone, date');
		$this->db->select('*');
		$this->db->from('reserves');
		$this->db->join('schedule','schedule.reserves_id = reserves.id');
		$this->db->join('offer','reserves.offer_id = offer.id');
		$this->db->join('reserve','reserve.reserves_id = reserves.id');
		$this->db->join('client','reserve.client_id = client.id');
		//$this->db->where('schedule.reserves_id',5);
		$this->db->where('reserves.id',5);
		//$this->db->where('reserves.offer_id',8);
		$result = $this->db->get()->result();
		return $result;
		
	}
	
	
	
	
	
	
	


	
	
	
	
	/**
	 * Flush data relative to Past Events.
	 * The field editable is set to '0' and the 'borderColor' is set to black 
	 * in the past events in order to avoid changes in these events.
	 * @param datetime $start 
	 * @param datetime $end
	 */
	public function flushPastEvents($start, $end) {
		
		// get current time (datetime)
		$now = date('Y-m-d H:i:s',time());
		
		// select 'id' ...
		$this->db->select('id');
		$this->db->from('schedule');
		$this->db->join('fullcalevent','fullcalevent.schedule_id = schedule.id'); // we need to join to get 'editable' column
		
		// .. in the given range
		$this->db->where('start >'	, $start);
		$this->db->where('end <'	, $end);
		
		// ... and before the actual date
		$this->db->where('start <'	, $now);
		
		// ... and only those fields who are editable.
		$this->db->where('editable',1);
		
		// get results
		$query = $this->db->get();
		$row = $query->result();
		
		// data to update
		$data = array(
			'editable' 		=> 0,
			'borderColor' 	=> 'black'
		);
		
		// update all items with previous data ... 
		foreach ($row as $item) {
			$this->db->update('fullcalevent',$data,array('schedule_id'=>$item->id));
		}
	}

	
	
	
	
	
	
	/**
	 * Flush Offer Data -
	 * Reset the remainingClasses field and set the participants number (part) to 0 in all offers that dont have
	 * any future schedules so these offers can be available again.
	 */
	public function flushOffers() {
		
		// id of the current user
		$user_id = $this->ion_auth->get_user()->id;
		
		// current time in datetime format
		$now = date('Y-m-d H:i:s',time());
		
		// offer's beeing used above the current date
		$inUseOfferID = array();
		
		// all offer ID's of the current user
		$allOfferID = array();
		
		// get offer id's beeing used above current date
		$this->db->select('offer.id');
		$this->db->from('offer');
		$this->db->join('schedule','schedule.offer_id = offer.id');
		$this->db->where('end >',$now);
		$query = $this->db->get();
		$row = $query->result();
		foreach ($row as $item) {
			array_push($inUseOfferID, $item->id);
		}
		$inUseOfferID = array_unique($inUseOfferID);
		
		// clear previous db results
		$this->db->flush_cache();
		$query = null; $row = null;
		
		// get all offers id's
		$this->db->select('id');
		$this->db->from('offer');
		$this->db->where('users_id',$user_id);
		$query = $this->db->get();
		$row = $query->result();
		foreach ($row as $item) {
			array_push($allOfferID, $item->id);
		}
		$allOfferID = array_unique($allOfferID);
		
		// get the array with offer id's to update 
		$toUpdateOfferID = array_diff($allOfferID, $inUseOfferID);
		
		// clear previous db results
		$this->db->flush_cache();
		$query = null; $row = null;
		
		// reset the remainingClasses field only if necessary 
		if (!empty($toUpdateOfferID)) {
			$this->db->select('id, numberOfClasses, remainingClasses');
			$this->db->from('offer');
			$this->db->where_in('id',$toUpdateOfferID);
			$query = $this->db->get();
			$row = $query->result();
			foreach ($row as $item) {
				$this->db->where('id',$item->id);
				// reset 'remainingClasses' with the value 'numberOfClasses' ... 
				// and reset the participant number to 0 ... check if it works
				$this->db->update('offer', array('remainingClasses'=>$item->numberOfClasses,'part'=>0), array('id'=>$item->id));
			}
		}
		else {
			
		}
	}
	
	
	public function past_offerIDs_not_full() {
		
	}

	/**
	 * @param array $defaults with fields and data that should be set to default if not present
	 * @param array $options where the default values must be placed
	 * @return array with the merged values
	 */
	private function _default($defaults, $options) {
		return array_merge($defaults, $options);
	}
	
	
	/**
	 * Checks if the array has all requiered fields
	 * @param array $required with the requiered fields
	 * @param array $data with the fields to be checked
	 * @return TRUE if the field exists FALSE otherwise
	 */
	private function _required($required, $data) {
		foreach ($required as $field)
			if (!isset($data[$field]))
			return false;
		return true;
	}
	
	
	
	
	
	public function flushClientReserves() {
		
		$offerIDs = array();
	
		// get reserves associated to offers with free spaces to fill
		$this->db->select('*')->from('reserve');
		$this->db->where('offer_tmp_id is not null');
		$result = $this->db->get()->result();
		
		if (empty($result))
			return;
		
		foreach ($result as $value) {
			array_push($offerIDs, $value->offer_tmp_id);
		}
		$offerIDs = array_unique($offerIDs);
		//$this->firephp->log($offerIDs,'offerIDs');
		
		// reset data
		$this->db->flush_cache();
		$result = null;
		
		$this->db->select('id as offerId, numberOfClasses, remainingClasses')->from('offer')->where_in('id',$offerIDs);
		$result = $this->db->get()->result();
		
		foreach ($result as $value) {
			
			//  if '0' means that this offer has passed with free spots left ... create the reserve to this offer
			if (!($value->numberOfClasses - $value->remainingClasses)) {
				//$this->firephp->log($value->offerId, 'create a reserve for this offer:');
			}
		}
	
		
		
	}
	
	
	//public function av
	
	
	
}